const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');
const auth = require('../middleware/auth');

// 获取今日考勤状态
router.get('/today', auth, async (req, res) => {
  try {
    const { userId } = req.query;
    const today = new Date().toISOString().split('T')[0];
    
    const [attendance] = await pool.execute(
      `SELECT a.*, c.name as courseName, c.startTime, c.endTime 
       FROM attendance a 
       LEFT JOIN courses c ON a.courseId = c.id 
       WHERE a.studentId = ? AND a.date = ?`,
      [userId, today]
    );

    res.json({
      hasCheckedIn: attendance.length > 0,
      hasCheckedOut: attendance.some(a => a.checkOutTime != null),
      checkinTime: attendance[0]?.checkInTime,
      checkoutTime: attendance[0]?.checkOutTime,
      currentCourseId: attendance[0]?.courseId
    });
  } catch (error) {
    console.error('获取考勤状态失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 签到
router.post('/checkin', auth, async (req, res) => {
  try {
    const { userId, courseId, sessionId, location } = req.body;
    
    console.log('签到请求参数:', req.body); // 添加日志
    
    if (!userId || !courseId || !sessionId || !location) {
      return res.status(400).json({ message: '缺少必要参数' });
    }
    
    // 获取用户信息
    const [userRows] = await pool.execute(
      `SELECT id, classId FROM users WHERE id = ? OR userId = ?`,
      [userId, userId]
    );
    
    if (userRows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    const studentId = userRows[0].id;
    const classId = userRows[0].classId;
    
    console.log('学生信息:', { studentId, classId }); // 添加日志
    
    // 检查会话是否存在且有效
    const [sessionRows] = await pool.execute(
      `SELECT id, courseId, classId, startTime, endTime, status 
       FROM teacher_signin_sessions 
       WHERE id = ? AND status = 'active'`,
      [sessionId]
    );
    
    if (sessionRows.length === 0) {
      return res.status(404).json({ message: '签到会话不存在或已结束' });
    }
    
    console.log('会话信息:', sessionRows[0]); // 添加日志
    
    // 检查是否已经签到
    const [existingAttendance] = await pool.execute(
      `SELECT id FROM attendance 
       WHERE studentId = ? 
       AND sessionId = ?`,
      [studentId, sessionId]
    );
    
    if (existingAttendance && existingAttendance.length > 0) {
      return res.status(400).json({ message: '您已经签到过了' });
    }
    
    // 记录签到
    await pool.execute(
      `INSERT INTO attendance 
       (studentId, courseId, classId, sessionId, date, status, checkInTime, location) 
       VALUES (?, ?, ?, ?, CURDATE(), 'present', NOW(), ?)`,
      [studentId, courseId, classId, sessionId, JSON.stringify(location)]
    );
    
    res.status(201).json({ 
      message: '签到成功',
      checkinTime: new Date().toISOString()
    });
  } catch (error) {
    console.error('签到失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 签退
router.post('/checkout', auth, async (req, res) => {
  try {
    const { userId, courseId, location } = req.body;
    
    // 更新签退信息
    const [result] = await pool.execute(
      `UPDATE attendance 
       SET checkOutTime = NOW(), 
           location = JSON_SET(location, '$.checkout', ?) 
       WHERE studentId = ? AND courseId = ? AND DATE(checkInTime) = CURDATE()`,
      [JSON.stringify(location), userId, courseId]
    );

    if (result.affectedRows === 0) {
      return res.status(400).json({ message: '未找到对应的签到记录' });
    }

    res.json({ 
      message: '签退成功',
      checkoutTime: new Date().toISOString()
    });
  } catch (error) {
    console.error('签退失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取考勤统计
router.get('/stats', auth, async (req, res) => {
  try {
    // 从req.user获取用户信息，而不是仅依赖query参数
    const userId = req.query.userId || req.user.id;
    const role = req.query.role || req.user.role;
    const { courseId, classId, date } = req.query;
    
    console.log('获取考勤统计请求参数:', req.query); // 添加日志
    
    let query = `
      SELECT 
        COUNT(CASE WHEN status = 'present' THEN 1 END) as normal,
        COUNT(CASE WHEN status = 'absent' THEN 1 END) as absent,
        COUNT(CASE WHEN status = 'late' THEN 1 END) as late,
        COUNT(CASE WHEN status = 'early' THEN 1 END) as early
      FROM attendance
      WHERE 1=1
    `;
    
    const params = [];
    
    if (role === 'student') {
      query += ` AND studentId = ?`;
      params.push(userId);
    } else if (role === 'teacher') {
      if (courseId) {
        query += ` AND courseId = ?`;
        params.push(courseId);
      }
      if (classId) {
        query += ` AND classId = ?`;
        params.push(classId);
      }
    }
    
    if (date) {
      query += ` AND DATE(checkInTime) = ?`;
      params.push(date);
    }

    console.log('统计查询SQL:', query); // 添加日志
    console.log('统计查询参数:', params); // 添加日志

    const [stats] = await pool.execute(query, params);
    console.log('统计结果:', stats[0]); // 添加日志
    
    res.json({
      normal: stats[0]?.normal || 0,
      late: stats[0]?.late || 0,
      early: stats[0]?.early || 0,
      absent: stats[0]?.absent || 0
    });
  } catch (error) {
    console.error('获取考勤统计失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 计算两点之间的距离（米）
function calculateDistance(lat1, lon1, lat2, lon2) {
  const R = 6371e3; // 地球半径（米）
  const φ1 = lat1 * Math.PI/180;
  const φ2 = lat2 * Math.PI/180;
  const Δφ = (lat2-lat1) * Math.PI/180;
  const Δλ = (lon2-lon1) * Math.PI/180;

  const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
          Math.cos(φ1) * Math.cos(φ2) *
          Math.sin(Δλ/2) * Math.sin(Δλ/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

  return R * c;
}

// 获取当前活动的签到会话
router.get('/active-session', auth, async (req, res) => {
  try {
    const { userId, courseId } = req.query;
    
    console.log('获取活动会话请求参数:', req.query); // 添加日志
    
    if (!userId) {
      return res.status(400).json({ 
        message: '缺少用户ID参数' 
      });
    }
    
    // 获取用户信息
    const [userRows] = await pool.execute(
      `SELECT id, userId, classId FROM users WHERE id = ? OR userId = ?`,
      [userId, userId]
    );
    
    if (userRows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    console.log('查询到的用户信息:', userRows[0]); // 添加日志
    
    const studentId = userRows[0].id;
    const classId = userRows[0].classId;
    
    // 构建查询条件
    let sessionQuery = `
      SELECT 
        tss.id,
        tss.courseId,
        tss.classId,
        tss.startTime,
        tss.endTime,
        tss.status,
        c.name as courseName,
        u.name as teacherName,
        a.id as attendanceId,
        a.checkInTime,
        a.checkOutTime
      FROM teacher_signin_sessions tss
      LEFT JOIN courses c ON tss.courseId = c.id
      LEFT JOIN users u ON tss.teacherId = u.id
      LEFT JOIN attendance a ON tss.id = a.sessionId AND a.studentId = ?
      WHERE tss.status = 'active'
        AND DATE(tss.startTime) = CURDATE()
    `;
    
    const params = [studentId];
    
    // 如果提供了课程ID，添加课程筛选条件
    if (courseId) {
      sessionQuery += ` AND tss.courseId = ?`;
      params.push(courseId);
    }
    
    // 如果有班级ID，添加班级筛选条件
    if (classId) {
      sessionQuery += ` AND tss.classId = ?`;
      params.push(classId);
    }
    
    console.log('会话查询SQL:', sessionQuery); // 添加日志
    console.log('会话查询参数:', params); // 添加日志
    
    const [sessionRows] = await pool.execute(sessionQuery, params);
    
    console.log('查询到的会话数量:', sessionRows.length); // 添加日志
    console.log('会话数据:', sessionRows); // 添加日志
    
    if (sessionRows.length === 0) {
      // 如果没有找到会话，尝试查询所有活动会话（不限制班级和课程）
      const [allSessions] = await pool.execute(
        `SELECT 
          tss.id,
          tss.courseId,
          tss.classId,
          tss.startTime,
          tss.endTime,
          tss.status,
          c.name as courseName,
          u.name as teacherName
         FROM teacher_signin_sessions tss
         LEFT JOIN courses c ON tss.courseId = c.id
         LEFT JOIN users u ON tss.teacherId = u.id
         WHERE tss.status = 'active'
           AND DATE(tss.startTime) = CURDATE()
         LIMIT 5`,
        []
      );
      
      console.log('所有活动会话:', allSessions); // 添加日志
      
      return res.json(null); // 当前没有课程
    }
    
    const session = sessionRows[0];
    
    res.json({
      courseId: session.courseId,
      courseName: session.courseName,
      teacherName: session.teacherName,
      sessionId: session.id,
      startTime: session.startTime,
      endTime: session.endTime,
      hasCheckedIn: session.attendanceId ? true : false,
      checkinTime: session.checkInTime,
      checkoutTime: session.checkOutTime,
      status: 'active'
    });
    
  } catch (error) {
    console.error('获取活动签到会话失败:', error);
    res.status(500).json({ 
      message: '服务器错误',
      error: error.message 
    });
  }
});

// 获取学生考勤记录
router.get('/student', auth, async (req, res) => {
  try {
    const { userId, dateRange, status } = req.query;
    
    if (!userId) {
      return res.status(400).json({ message: '缺少用户ID参数' });
    }
    
    // 构建查询条件
    let query = `
      SELECT 
        a.id,
        a.date,
        a.status,
        a.checkInTime,
        a.checkOutTime,
        a.location,
        a.remark,
        c.name as courseName
      FROM attendance a
      LEFT JOIN courses c ON a.courseId = c.id
      WHERE a.studentId = ?
    `;
    
    const params = [userId];
    
    // 添加日期范围过滤
    if (dateRange) {
      const today = new Date();
      const startDate = new Date();
      
      if (dateRange === '本周') {
        // 计算本周的开始日期（周一）
        const day = today.getDay() || 7;
        startDate.setDate(today.getDate() - day + 1);
        query += ` AND a.date >= ?`;
        params.push(startDate.toISOString().split('T')[0]);
      } else if (dateRange === '本月') {
        // 设置为本月第一天
        startDate.setDate(1);
        query += ` AND a.date >= ?`;
        params.push(startDate.toISOString().split('T')[0]);
      } else if (dateRange === '本学期') {
        // 假设学期从2月或9月开始
        const month = today.getMonth() + 1;
        if (month >= 2 && month < 9) {
          // 春季学期 2月-7月
          startDate.setMonth(1); // 2月
          startDate.setDate(1);
        } else {
          // 秋季学期 9月-1月
          startDate.setMonth(8); // 9月
          startDate.setDate(1);
        }
        query += ` AND a.date >= ?`;
        params.push(startDate.toISOString().split('T')[0]);
      }
    }
    
    // 添加状态过滤
    if (status) {
      let dbStatus = '';
      switch (status) {
        case '正常':
          dbStatus = 'present';
          break;
        case '迟到':
          dbStatus = 'late';
          break;
        case '早退':
          dbStatus = 'early';
          break;
        case '缺勤':
          dbStatus = 'absent';
          break;
      }
      
      if (dbStatus) {
        query += ` AND a.status = ?`;
        params.push(dbStatus);
      }
    }
    
    // 按日期降序排序
    query += ` ORDER BY a.date DESC, a.checkInTime DESC`;
    
    // 执行查询
    const [records] = await pool.execute(query, params);
    
    // 统计各类考勤数量
    const [statsResult] = await pool.execute(
      `SELECT 
        COUNT(*) as total,
        COUNT(CASE WHEN status = 'present' THEN 1 END) as normal,
        COUNT(CASE WHEN status = 'late' THEN 1 END) as late,
        COUNT(CASE WHEN status = 'early' THEN 1 END) as early,
        COUNT(CASE WHEN status = 'absent' THEN 1 END) as absent
      FROM attendance
      WHERE studentId = ?`,
      [userId]
    );
    
    // 格式化记录
    const formattedRecords = records.map(record => {
      // 格式化日期
      const date = record.date ? new Date(record.date).toISOString().split('T')[0] : '';
      
      // 格式化签到时间
      let checkInTime = '';
      if (record.checkInTime) {
        const checkIn = new Date(record.checkInTime);
        checkInTime = `${checkIn.getHours().toString().padStart(2, '0')}:${checkIn.getMinutes().toString().padStart(2, '0')}`;
      }
      
      // 格式化签退时间
      let checkOutTime = '';
      if (record.checkOutTime) {
        const checkOut = new Date(record.checkOutTime);
        checkOutTime = `${checkOut.getHours().toString().padStart(2, '0')}:${checkOut.getMinutes().toString().padStart(2, '0')}`;
      }
      
      // 格式化状态
      let statusText = '';
      switch (record.status) {
        case 'present':
          statusText = '正常';
          break;
        case 'late':
          statusText = '迟到';
          break;
        case 'early':
          statusText = '早退';
          break;
        case 'absent':
          statusText = '缺勤';
          break;
        case 'leave':
          statusText = '请假';
          break;
        default:
          statusText = record.status;
      }
      
      // 解析位置信息
      let location = record.remark || '未知位置';
      if (record.location) {
        try {
          const locationObj = typeof record.location === 'string' ? JSON.parse(record.location) : record.location;
          location = locationObj.address || locationObj.name || record.remark || '未知位置';
        } catch (e) {
          console.error('解析位置信息失败:', e);
        }
      }
      
      return {
        id: record.id,
        date: date,
        checkInTime: checkInTime,
        checkOutTime: checkOutTime,
        status: statusText,
        location: location,
        courseName: record.courseName || '未知课程'
      };
    });
    
    res.json({
      success: true,
      records: formattedRecords,
      stats: {
        total: statsResult[0].total || 0,
        normal: statsResult[0].normal || 0,
        late: statsResult[0].late || 0,
        early: statsResult[0].early || 0,
        absent: statsResult[0].absent || 0
      }
    });
  } catch (error) {
    console.error('获取考勤记录失败:', error);
    res.status(500).json({ 
      success: false,
      message: '服务器错误',
      error: error.message 
    });
  }
});



// 添加获取班级考勤统计的接口

// 获取班级考勤统计
router.get('/class-stats', auth, async (req, res) => {
  try {
    const { classId, courseId, date } = req.query;
    
    if (!classId) {
      return res.status(400).json({ message: '缺少班级ID参数' });
    }
    
    // 获取班级总人数
    const [classStudents] = await pool.execute(
      `SELECT COUNT(*) as total FROM users WHERE classId = ? AND role = 'student'`,
      [classId]
    );
    
    const totalStudents = classStudents[0].total;
    console.log(`班级 ${classId} 的学生总数: ${totalStudents}`);
    
    // 构建查询条件
    let query = `
        SELECT 
        COUNT(CASE WHEN status = 'present' THEN 1 END) as present,
        COUNT(CASE WHEN status = 'late' THEN 1 END) as late,
        COUNT(CASE WHEN status = 'early' THEN 1 END) as early,
        COUNT(CASE WHEN status = 'absent' THEN 1 END) as absent,
        COUNT(CASE WHEN status = 'leave' THEN 1 END) as \`leave\`
      FROM attendance
      WHERE classId = ?
    `;
    
    const params = [classId];
    
    // 添加课程筛选
    if (courseId) {
      query += ` AND courseId = ?`;
      params.push(courseId);
    }
    
    // 添加日期筛选
    if (date) {
      query += ` AND DATE(date) = ?`;
      params.push(date);
    } else {
      // 默认查询今天的数据
      query += ` AND DATE(date) = CURDATE()`;
    }
    
    console.log('执行SQL查询:', query, params);
    
    const [stats] = await pool.execute(query, params);
    
    // 计算缺勤人数（总人数减去已签到、请假的人数）
    const checkedIn = (stats[0]?.present || 0) + (stats[0]?.late || 0) + (stats[0]?.early || 0);
    const absent = totalStudents - checkedIn - (stats[0]?.leave || 0);
    
    res.json({
      success: true,
      stats: {
        total: totalStudents,
        checkedIn: checkedIn,
        present: stats[0]?.present || 0,
        late: stats[0]?.late || 0,
        early: stats[0]?.early || 0,
        absent: absent < 0 ? 0 : absent,
        leave: stats[0]?.leave || 0
      }
    });
    
  } catch (error) {
    console.error('获取班级考勤统计失败:', error);
    res.status(500).json({ 
      success: false,
      message: '服务器错误',
      error: error.message 
    });
  }
});

// 教师发起考勤
router.post('/start-session', auth, async (req, res) => {
  try {
    const { courseId, classId, location, duration } = req.body;
    const teacherId = req.user.id;
    
    if (!courseId || !classId) {
      return res.status(400).json({ success: false, message: '缺少必要参数' });
    }
    
    // 获取班级总人数
    const [classStudents] = await pool.execute(
      `SELECT COUNT(*) as total FROM users WHERE classId = ? AND role = 'student'`,
      [classId]
    );
    
    const totalStudents = classStudents[0].total;
    
    // 创建考勤会话
    const [result] = await pool.execute(
      `INSERT INTO teacher_signin_sessions 
       (teacherId, courseId, classId, startTime, endTime, location, status) 
       VALUES (?, ?, ?, NOW(), DATE_ADD(NOW(), INTERVAL ? MINUTE), ?, 'active')`,
      [teacherId, courseId, classId, duration || 30, JSON.stringify(location)]
    );
    
    const sessionId = result.insertId;
    
    res.status(201).json({
      success: true,
      message: '考勤会话创建成功',
      sessionId: sessionId,
      stats: {
        total: totalStudents,
        checkedIn: 0,
        absent: totalStudents,
        leave: 0
      }
    });
    
  } catch (error) {
    console.error('创建考勤会话失败:', error);
    res.status(500).json({ 
      success: false,
      message: '服务器错误',
      error: error.message 
    });
  }
});
// 更新考勤会话状态
router.post('/update-session-status', auth, async (req, res) => {
  try {
    const { sessionId, status } = req.body;
    const teacherId = req.user.id;
    
    if (!sessionId || !status) {
      return res.status(400).json({ 
        success: false, 
        message: '缺少必要参数' 
      });
    }
    
    // 验证状态值
    if (status !== 'active' && status !== 'closed') {
      return res.status(400).json({ 
        success: false, 
        message: '无效的状态值' 
      });
    }
    
    // 验证会话是否存在且属于该教师
    const [sessionCheck] = await pool.execute(
      `SELECT id FROM teacher_signin_sessions WHERE id = ? AND teacherId = ?`,
      [sessionId, teacherId]
    );
    
    if (sessionCheck.length === 0) {
      return res.status(403).json({ 
        success: false, 
        message: '无权操作此考勤会话' 
      });
    }
    
    // 更新会话状态
    const updateQuery = `
      UPDATE teacher_signin_sessions 
      SET status = ?, 
          ${status === 'closed' ? 'endTime = NOW()' : 'endTime = DATE_ADD(NOW(), INTERVAL 30 MINUTE)'}
      WHERE id = ?
    `;
    
    await pool.execute(updateQuery, [status, sessionId]);
    
    res.json({
      success: true,
      message: status === 'active' ? '考勤会话已重启' : '考勤会话已结束'
    });
    
  } catch (error) {
    console.error('更新考勤会话状态失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器错误',
      error: error.message 
    });
  }
});

module.exports = router;